// 注册页-业务模块

import axios from 'axios';
import {$} from './utils.js';

// 点击 send 发送验证码
$('#send').onclick = function (){
    // 获取输入的邮箱
    let email = $('#email').value;

    // 校验邮箱格式
    let reg = /^\w{6,18}@[0-9a-zA-Z]{1,12}(\.[a-zA-Z]{2,3}){1,2}$/;
    if (!reg.test(email)) {
        alert('邮箱格式错误！');
        return;
    }

    // 发送请求
    axios({
        method: 'get',
        url: 'http://localhost:9090/users/sendmail',
        params: {email}
    })
    .then((response)=>{
        let {data} = response;
        alert(data.msg);
    })
    .catch(()=>{
        alert('网络异常，请重试！');
    });
};

// 点击 register 发送注册请求
$('#register').onclick = function (){
    // 获取用户输入的内容
    let user = $('#user').value;
    let pass = $('#pass').value;
    let nick = $('#nick').value;
    let email = $('#email').value;
    let code = $('#code').value;
    let age = $('#age').value;
    let sex = $('#sex').value;

    // 校验数据(简单的做空值判断)
    if (!user || !pass || !nick || !email || !code || !age || !sex) {
        alert('注册内容不能为空！');
        return;
    }

    // 发送注册请求
    axios({
        method: 'post',
        url: 'http://localhost:9090/users/register',
        data: {
            username: user,
            password: pass,
            nickname: nick,
            email,
            age,
            sex,
            code
        }
    })
    .then((response)=>{
        let {data} = response;
        alert(data.msg);
        if (data.code === 1) {
            // 注册成功，跳转到登录页
            location.href = './login.html';
        }
    })
    .catch(()=>{
        alert('网络异常，请重试！');
    });
};